package com.mocoder.chatdemo.model;

import java.io.ByteArrayInputStream;
import java.util.Arrays;

import com.mocoder.chatdemo.util.ByteUtil;
import javafx.scene.image.Image;

/**
 * Created by Administrator on 2018/3/10.
 */
public class UserInfo {

    private String name;
    private byte[] photoData;
    private long updateTime;
    private transient Image photoImage;

    public UserInfo() {
    }

    public UserInfo(String name, byte[] photoData, long updateTime) {
        this.name = name;
        this.photoData = photoData;
        this.updateTime = updateTime;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public byte[] getPhotoData() {
        return photoData;
    }

    public void setPhotoData(byte[] photoData) {
        this.photoData = photoData;
        photoImage = null;
    }

    public long getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(long updateTime) {
        this.updateTime = updateTime;
    }

    public Image genPhotoImage() {
        if (photoImage == null && photoData != null && photoData.length != 0) {
            ByteArrayInputStream input = new ByteArrayInputStream(getPhotoData());
            photoImage = new Image(input, 40, 40, true, true);
        }
        return photoImage;
    }

    public static byte[] encode(UserInfo userInfo, boolean ifReq) {
        byte[] name = userInfo.getName() == null ? new byte[0] : ByteUtil.str2byte(userInfo.getName());
        byte[] photo = userInfo.getPhotoData() == null ? new byte[0] : userInfo.getPhotoData();
        byte[] bytes = ByteUtil.join(ifReq ? ByteUtil.HEADER_USERSCAN_REQ : ByteUtil.HEADER_USERSCAN_RES,
            ByteUtil.int2byte(name.length), name,
            ByteUtil.int2byte(photo.length), photo,
            ByteUtil.long2byte(userInfo.getUpdateTime())
        );
        return bytes;
    }

    public static UserInfo decode(byte[] bytes) {
        int index = 5;
        int len = ByteUtil.byte2int(bytes, index);
        index += 4;
        String name = ByteUtil.byte2str(bytes, index, len);
        index += len;
        len = ByteUtil.byte2int(bytes, index);
        index += 4;
        byte[] photo = Arrays.copyOfRange(bytes, index, index + len);
        index += len;
        UserInfo userInfo = new UserInfo(name, photo, ByteUtil.byte2long(bytes, index));
        return userInfo;
    }
}
